package com.gitee.feizns.quickstart.web.Interceptors.bucket4j;

import com.gitee.feizns.dynamic.decrypt.Encrypts;
import com.gitee.feizns.quickstart.web.WebUtils;
import io.github.bucket4j.Bucket;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * {@link Bucket}
 * @author feizns
 * @since 2025/10/22
 */
public interface RateLimitHandler {

    /**
     * 带宽
     */
    Bucket bucket(String key);

    /**
     * 请求唯一标识
     * @return {@link String }
     */
    default String key() {
        HttpServletRequest req = WebUtils.getReq();
        String method = req.getMethod();
        String path = WebUtils.getReq().getRequestURI();
        String query = Objects.toString(req.getQueryString(), "");
        String userAgent = WebUtils.getUserAgent();
        String ip = WebUtils.getIpAddress();
        return md5(method, path, query, userAgent, ip);
    }

    /**
     * 如果超过则抛出
     */
    default void throwIfExceeded(Bucket bucket) {
        if ( !bucket.tryConsume(1) )
            throw new RateLimitException("请求到达上限！请稍后重试！！！");
    }

    /**
     * 标识hash
     * @param args 参数
     * @return {@link String }
     */
    static String md5(String... args) {
        return Encrypts.md5(String.join(":", args));
    }

}
